﻿using System;
using InfoJetSoft.Service.Entity;

namespace InfoJetSoft.Service.Util
{
    /// <summary>
    /// Summary description for DataAdapterTableUtil.
    /// </summary>
    class DataAdapterTableUtil
    {

        //在ManagedCode命名空间中调用，总是返回一个Clone的Adapter用于Form Code修改
        public static object getCurrentAdapter(Form form, ICloneable templateAdapter)
        {
            /*
             * 因为在代码中可能修改这些内容，所以需要Clone。
             * 如果在DataAdapterTable中找不到,则Clone一个。
             */
            object currentAdapter = form.DataAdapterTable[templateAdapter];
            if (currentAdapter == null)
            {
                currentAdapter = templateAdapter.Clone();
                form.DataAdapterTable.Add(templateAdapter, currentAdapter);
            }
            return currentAdapter;
        }

        public static object getTemplateAdapter(Form form, ICloneable currentAdapter)
        {
            foreach (object key in form.DataAdapterTable.Keys)
            {
                object val = form.DataAdapterTable[key];
                if (val != null && val.Equals(currentAdapter))
                {
                    return key;
                }
            }
            return null;
        }

        //如果存在Clone的Adapter，则返回Clone的，没有则返回传入的adapter，即adapter没有在Form Code中修改。
        //也就是说,如果在Form Code中修改DataAdapter,必须先使用getCurrentAdapter的到复制的DataAdapter.
        //而且这个复制出来的DataAdapter将被存储在DataAdapterTable中,并这次Request调用中都将使用这个DataAdapter.
        public static object getAvaliableAdapter(Form form, object adapter)
        {
            object currentAdapter = form.DataAdapterTable[adapter];
            if (currentAdapter == null)
            {
                return adapter;
            }
            return currentAdapter;
        }

    }
}
